# -*- mode: python ; coding: utf-8 -*-

import os
import sys

try:
    import PyQt5
    pyqt_path = os.path.dirname(PyQt5.__file__)
    if pyqt_path not in sys.path:
        sys.path.append(pyqt_path)
except ImportError:
    raise SystemExit("错误：PyQt5 未安装，请先运行 'pip install PyQt5'")

from PyInstaller.building.build_main import Analysis, EXE, PYZ

# 获取项目根目录绝对路径
project_root = os.path.dirname(os.path.abspath(SPEC))
project_root = os.path.join(project_root, '..')

block_cipher = None

required_hidden_imports = [
    'PyQt5',
    'PyQt5.QtCore',
    'PyQt5.QtGui',
    'PyQt5.QtWidgets',
    'PyQt5.sip',
    'PyQt5.QtNetwork',
    'urllib3.packages.six.moves',
    'brotli',
    'dotenv',
    'sqlite3',
    'certifi',
    'cryptography.hazmat.backends.openssl',
]

def collect_assets():
    asset_files = []
    assets_dir = os.path.join(project_root, 'assets')
    if not os.path.exists(assets_dir):
        print(f"警告：assets 目录不存在: {assets_dir}")
        return []
    
    for root, _, files in os.walk(assets_dir):
        for file in files:
            src_path = os.path.join(root, file)
            dest_path = os.path.relpath(root, start=project_root)
            # 注意：这里使用二元组格式 (src, dest)
            asset_files.append((src_path, dest_path))
    return asset_files

# 主分析配置
a = Analysis(
    [os.path.join(project_root, 'desktop_app', 'main.py')],
    pathex=[project_root, pyqt_path],
    binaries=[],
    datas=[
        (os.path.join(project_root, '.env'), '.'),  # 二元组格式
        *collect_assets(),
    ],
    hiddenimports=required_hidden_imports,
    hookspath=[],
    runtime_hooks=[],
    excludes=[],
    win_no_prefer_redirects=False,
    win_private_assemblies=False,
    cipher=block_cipher,
    noarchive=False,
)

# 添加Qt插件
if hasattr(PyQt5, '__file__'):
    qt_plugin_path = os.path.join(os.path.dirname(PyQt5.__file__), 'Qt', 'plugins')
    qwindows_dll = os.path.join(qt_plugin_path, 'platforms', 'qwindows.dll')
    
    if os.path.exists(qwindows_dll):
        # 注意：二进制文件使用 append 方式添加
        a.binaries.append(
            (os.path.join('PyQt5', 'Qt', 'plugins', 'platforms'), qwindows_dll, 'BINARY')
        )

pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher)

exe = EXE(
    pyz,
    a.scripts,
    a.binaries,
    a.zipfiles,
    a.datas,
    name='VideoAnalyzer',
    debug=False,
    bootloader_ignore_signals=False,
    strip=False,
    upx=True,
    upx_exclude=[],
    runtime_tmpdir=None,
    console=False,#True 可调试打包后的东西
    icon=None,
    onefile=True,
)